package top.xmj.service.impl;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import top.xmj.exception.BusinessException;
import top.xmj.exception.SystemException;
import top.xmj.service.IMailService;
import top.xmj.util.DateFormatUtils;
import top.xmj.util.RedisUtil;
import top.xmj.util.VerificationCodeUtil;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 冰咖啡
 * Date:4/12/2022 下午 2:23
 * Description:
 */
@Service
public class MailServiceImpl implements IMailService {
        private static final Logger logger = LoggerFactory.getLogger(top.xmj.service.IMailService.class);

        @Autowired
        private JavaMailSender mailSender;

        @Autowired
        private RedisUtil redisUtil;

        @Autowired
        private VerificationCodeUtil verificationCodeUtil;

        /**
         * 注入邮件工具类
         */
        @Autowired
        private JavaMailSenderImpl javaMailSender;

        @Value("${spring.mail.username}")
        private String sendMailer;

        /**
         * 检测邮件信息类
         * @param to
         * @param subject
         * @param text
         */
        @Override
        public void checkMail(String to, String subject, String text){
            if(StringUtils.isEmpty(to)){
                throw new RuntimeException("邮件收信人不能为空");
            }
            if(StringUtils.isEmpty(subject)){
                throw new RuntimeException("邮件主题不能为空");
            }
            if(StringUtils.isEmpty(text)){
                throw new RuntimeException("邮件内容不能为空");
            }
        }

        /**
         * 发送纯文本邮件
         * @param to
         */
        @Override
        public String sendTextMailMessage(String to){
            String subject = "欢迎使用FrogChat!";
            String code = verificationCodeUtil.VerificationCode();
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String time = sdf.format(new Date());
            String key = "code-"+to;
            String oldCode = (String) redisUtil.get(key);
            String text = "<html>\n"+"<body>\n"
                    + "<h3>您的验证码是："+ code+"</h3>\n"
                    +"</body>\n"+"</html>";
            logger.info("邮件发送验证码："+code);
            if(oldCode!=null){
                throw new BusinessException(405, "邮件已经发送，一小时有效，请注意查收！");
            }
            try {
                //true 代表支持复杂的类型
                MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(javaMailSender.createMimeMessage(),true);
                //邮件发信人
                mimeMessageHelper.setFrom(sendMailer);
                //邮件收信人  1或多个
                mimeMessageHelper.setTo(to.split(","));
                //邮件主题
                mimeMessageHelper.setSubject(subject);
                //邮件内容
                mimeMessageHelper.setText(text);
                //邮件发送时间
                mimeMessageHelper.setSentDate(new Date());
                //发送邮件
                javaMailSender.send(mimeMessageHelper.getMimeMessage());
                System.out.println("发送邮件成功："+sendMailer+"->"+to);

            } catch (MessagingException e) {
                e.printStackTrace();
                throw new SystemException(500,"发送邮件失败："+e.getMessage());
            }
            boolean res =  redisUtil.set(key,code,10);
            if(!res){
                throw new BusinessException(500,"数据库发送了错误");
            }
            return code;
        }

//    @Override
//    public MailCode sendHTMlMailMessage(String to) {
//        String subject = "欢迎使用FrogChat!";
//        String code = VerificationCodeUtil.VerificationCode();
//        SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddHH");
//        String newS = sdf.format(new Date());
//        String key = newS+"-"+to;
//        //判断邮件是否重复发送(一个小时内
//        MailCode mailCode = new MailCode(key,to,code,new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()));
//        MailCode mailCode1 = mailCodeMapper.getMailCode(mailCode.getId());
//        String content = "<div style=\"background-color:#ECECEC; padding: 35px;\">\n" +
//                "    <table cellpadding=\"0\" align=\"center\"\n" +
//                "        style=\"width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;\">\n" +
//                "        <tbody>\n" +
//                "            <tr>\n" +
//                "                <th valign=\"middle\"\n" +
//                "                    style=\"height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #07C160; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;\">\n" +
//                "                    <font face=\"微软雅黑\" size=\"5\" style=\"color: rgb(255, 255, 255); \">欢迎注册 FrogChat</font>\n" +
//                "                </th>\n" +
//                "            </tr>\n" +
//                "            <tr>\n" +
//                "                <td>\n" +
//                "                    <div style=\"padding:25px 35px 40px; background-color:#fff;\">\n" +
//                "                        <h2 style=\"margin: 5px 0px; \">\n" +
//                "                            <font color=\"#333333\" style=\"line-height: 20px; \">\n" +
//                "                                <font style=\"line-height: 22px; \" size=\"4\">\n" +
//                "                                    首先感谢您加入FrogChat！</font>\n" +
//                "                            </font>\n" +
//                "                        </h2>\n" +
//                "                        <p>FrogChat是一款通用聊天的Web应用，为用户提供多功能实用工具箱。我们的期望是，让用户无需安装，即可实现多个功能，满足一天生活所需。\n" +
//                "                            FrogChat提供的各个工具之间互联互通、方便易用。 精彩的一天，从这里开始！<br>\n" +
//                "                        <h2>您的验证码为：</h2>\n" +
//                "                        <h1 style=\"text-align: center\">"+code+"</h1>\n" +
//                "                        您的邮箱："+to+"<br>\n" +
//                "                        当您在使用本平台时，遵守当地法律法规。<br>\n" +
//                "                        如果您有什么疑问可以联系管理员，Email: <b>1966447213.com</b></p>\n" +
//                "                        <p align=\"right\">FrogChat官方</p>\n" +
//                "                        <p align=\"right\">"+mailCode.getTime()+" </p>\n" +
//                "                        <div style=\"width:700px;margin:0 auto;\">\n" +
//                "                            <div\n" +
//                "                                style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
//                "                                <p>此为系统邮件，请勿回复<br>\n" +
//                "                                    请保管好您的邮箱，避免账号被他人盗用\n" +
//                "                                </p>\n" +
//                "                                <p>©冰咖啡</p>\n" +
//                "                            </div>\n" +
//                "                        </div>\n" +
//                "                    </div>\n" +
//                "                </td>\n" +
//                "            </tr>\n" +
//                "        </tbody>\n" +
//                "    </table>\n" +
//                "</div>";
//        logger.info("邮件发送验证码："+code);
//        if(mailCode1!=null){
//            throw new BusinessException(405, "邮件已经发送，一小时有效，请注意查收！");
//        }
//        try {
//            MimeMessage mimeMessage = mailSender.createMimeMessage();
//            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
//            helper.setFrom(sendMailer);
//            helper.setTo(to);
//            helper.setSubject(subject);
//            helper.setText(content, true);
//            mailSender.send(mimeMessage);
//            logger.info("发送邮件成功："+sendMailer+"->"+to);
//        } catch (MessagingException e) {
//            e.printStackTrace();
//            throw new SystemException(500,"发送邮件失败："+e.getMessage());
//        }
//        logger.info("===>mailCode:"+mailCode);
//        int res =  mailCodeMapper.addMailCode(mailCode);
//        if(res!=1){
//            throw new BusinessException(500,"数据库发送了错误");
//        }
//        return mailCode;
//    }

    @Override
    public String sendHTMlMailMessage(String to) {
        String subject = "欢迎使用FrogChat!";
        String code = verificationCodeUtil.VerificationCode();
        String time = DateFormatUtils.getDate(new Date(),"yyyy年MM月dd日 HH:mm:ss");
        String key = "code-"+to;
        String oldCode = (String) redisUtil.get(key);
        String content = "<div style=\"background-color:#ECECEC; padding: 35px;\">\n" +
                "    <table cellpadding=\"0\" align=\"center\"\n" +
                "        style=\"width: 600px; margin: 0px auto; text-align: left; position: relative; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 5px; border-bottom-left-radius: 5px; font-size: 14px; font-family:微软雅黑, 黑体; line-height: 1.5; box-shadow: rgb(153, 153, 153) 0px 0px 5px; border-collapse: collapse; background-position: initial initial; background-repeat: initial initial;background:#fff;\">\n" +
                "        <tbody>\n" +
                "            <tr>\n" +
                "                <th valign=\"middle\"\n" +
                "                    style=\"height: 25px; line-height: 25px; padding: 15px 35px; border-bottom-width: 1px; border-bottom-style: solid; border-bottom-color: #42a3d3; background-color: #07C160; border-top-left-radius: 5px; border-top-right-radius: 5px; border-bottom-right-radius: 0px; border-bottom-left-radius: 0px;\">\n" +
                "                    <font face=\"微软雅黑\" size=\"5\" style=\"color: rgb(255, 255, 255); \">欢迎注册 FrogChat</font>\n" +
                "                </th>\n" +
                "            </tr>\n" +
                "            <tr>\n" +
                "                <td>\n" +
                "                    <div style=\"padding:25px 35px 40px; background-color:#fff;\">\n" +
                "                        <h2 style=\"margin: 5px 0px; \">\n" +
                "                            <font color=\"#333333\" style=\"line-height: 20px; \">\n" +
                "                                <font style=\"line-height: 22px; \" size=\"4\">\n" +
                "                                    首先感谢您加入FrogChat！</font>\n" +
                "                            </font>\n" +
                "                        </h2>\n" +
                "                        <p>FrogChat是一款通用聊天的Web应用，为用户提供多功能实用工具箱。我们的期望是，让用户无需安装，即可实现多个功能，满足一天生活所需。\n" +
                "                            FrogChat提供的各个工具之间互联互通、方便易用。 精彩的一天，从这里开始！<br>\n" +
                "                        <h2>您的验证码为：</h2>\n" +
                "                        <h1 style=\"text-align: center\">"+code+"</h1>\n" +
                "                        您的邮箱："+to+"<br>\n" +
                "                        当您在使用本平台时，遵守当地法律法规。<br>\n" +
                "                        如果您有什么疑问可以联系管理员，Email: <a href='mailto:1966447213@qq.com'><b>1966447213@qq.com</b></a></p>\n" +
                "                        <p align=\"right\">FrogChat官方</p>\n" +
                "                        <p align=\"right\">"+time+" </p>\n" +
                "                        <div style=\"width:700px;margin:0 auto;\">\n" +
                "                            <div\n" +
                "                                style=\"padding:10px 10px 0;border-top:1px solid #ccc;color:#747474;margin-bottom:20px;line-height:1.3em;font-size:12px;\">\n" +
                "                                <p>此为系统邮件，请勿回复<br>\n" +
                "                                    请保管好您的邮箱，避免账号被他人盗用\n" +
                "                                </p>\n" +
                "                                <p>©冰咖啡</p>\n" +
                "                            </div>\n" +
                "                        </div>\n" +
                "                    </div>\n" +
                "                </td>\n" +
                "            </tr>\n" +
                "        </tbody>\n" +
                "    </table>\n" +
                "</div>";
        if(oldCode!=null){
            throw new BusinessException(405, "邮件已经发送，十分钟有效，请注意查收！");
        }
        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(sendMailer);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            mailSender.send(mimeMessage);
            logger.info("发送邮件成功："+sendMailer+"->"+to);
            logger.info("邮件发送验证码："+code);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw new SystemException(500,"发送邮件失败："+e.getMessage());
        }
        boolean res =  redisUtil.set(key,code,10);
        if(!res){
            throw new BusinessException(500,"数据库发送了错误");
        }
        return code;
    }
}

